package com.woniu.util;

import com.woniu.dto.TreeDTO;
import com.woniu.dto.TreegridDTO;
import com.woniu.pojo.Auth;

import java.util.ArrayList;
import java.util.List;

public class TreeUtils {
    /**
     * @param authIds  默认拥有的权限ID
     * @param list     所有tree节点需要的数据集合
     * @param parentId 节点的父Id；根据该父Id构造子节点
     * @return
     */
    public static List<TreeDTO> buildTree(String authIds, List<Auth> list, Integer parentId) {

        List authList = new ArrayList();
        for (Auth auth : list) {
            if (auth.getParentId().equals(parentId)) {
                TreeDTO dto = new TreeDTO();
                dto.setId(auth.getAuthId());
                dto.setState(auth.getState());
                dto.setText(auth.getAuthName());
                dto.setIconCls(auth.getIconCls());
                if (authIds != null) {
                    String[] ids = authIds.split(",");
                    Integer[] arr = new Integer[ids.length];
                    for (int i = 0; i < arr.length; i++) {
                        arr[i] = Integer.parseInt(ids[i]);
                        if (auth.getAuthId().equals(arr[i])) {
                            //默认选中拥有权限的节点
                            dto.setChecked(true);
                        }
                    }
                }
                dto.setChildren(buildTree(authIds, list, auth.getAuthId()));
                authList.add(dto);
            }
        }
        return authList;
    }

    public static List<TreegridDTO> buildTreegrid(List<Auth> list, Integer parentId) {
        List authList = new ArrayList();
        for (Auth auth : list) {
            if (auth.getParentId().equals(parentId)) {
                TreegridDTO dto = new TreegridDTO();
                dto.setAuthDescription(auth.getAuthDescription());
                dto.setAuthId(auth.getAuthId());
                dto.setAuthName(auth.getAuthName());
                dto.setAuthPath(auth.getAuthPath());
                dto.setIconCls(auth.getIconCls());
                dto.setChildren(buildTreegrid(list, auth.getAuthId()));
                authList.add(dto);
            }
        }
        return authList;
    }
}
